<template>
  <div class="step3-action">
    <a-modal
      :visible="visible"
      :title="title"
      :closable="false"
      dialogClass="step3-action-modal"
      :width="720"
      @cancel="closeModal"
    >
      <a-form
        :form="form"
        labelAlign="left"
        :label-col="{ span: lang ? 8 : 11 }"
        :wrapper-col="{ span: lang ? 16 : 13 }"
      >
        <step-3-action-form
          ref="step3ActionForm"
          :ifCanEdit="ifCanEdit"
          :lang="lang"
          :status="status"
          :actionDetails="actionDetails"
          :ifAgree="ifAgree"
          :role="childRole"
          :form="form"
          :currentData="currentData"
          :initBmwList="initBmwList"
          @changeProp="changeProp"
        />
      </a-form>
      <email
        v-if="childRole.includes('processor')"
        type="corner"
        :cornerImg="type === 'new' ? 'letter' : 'letterSuccess'"
        :disabled="!ifCanEdit"
        :defaultUser="defaultUser"
        :actionList="actionList"
      />
      <template slot="footer">
        <div class="buttons">
          <!-- 保存草稿 -->
          <a-button
            type="primary"
            class="mr-[20px]"
            v-if="status !== 4"
            :disabled="!ifCanEdit"
            @click="submit('draft')"
            >{{ $t("user.register-result.view-mailbox") }}</a-button
          >
          <!-- 重启 -->
          <a-button
            v-if="status === 4 && childRole.includes('processor')"
            @click="submit('restart')"
            class="mr-[20px]"
            type="primary"
            >{{ $t("breach.steps.step3.action.new.buttons.restart") }}</a-button
          >
          <!-- 取消 -->
          <a-button
            @click="closeModal"
            :class="status === 4 ? '' : 'mr-[20px]'"
            >{{ $t("app.setting.content-width.fluid2222333") }}</a-button
          >
          <!-- 分配 -->
          <a-button
            v-if="
              (status === 1 || status === 3) &&
              (childRole.includes('processor') ||
                childRole.includes('shareEdit'))
            "
            type="primary"
            class="mr-[20px]"
            :disabled="!ifCanEdit"
            @click="submit('patch')"
            >{{ $t("breach.steps.step3.action.new.buttons.patch") }}</a-button
          >
          <!-- owner - 提交 -->
          <a-button
            v-if="status === 3 && childRole.includes('owner')"
            type="primary"
            :disabled="!ifCanEdit"
            @click="submit('ownerSubmit')"
            >{{ $t("user.register-result.back-home") }}</a-button
          >
          <!-- approver - 提交 -->
          <a-button
            v-if="status === 2 && ifAgree === 1"
            type="primary"
            :disabled="!ifCanEdit"
            @click="submit('approverSubmit')"
            >{{ $t("user.register-result.back-home") }}</a-button
          >
          <!-- 回退 -->
          <a-button
            v-if="status === 2 && ifAgree !== 1"
            type="primary"
            :disabled="!ifCanEdit"
            @click="submit('back')"
            >{{ $t("breach.steps.step3.action.new.buttons.back") }}</a-button
          >
        </div>
      </template>
    </a-modal>
    <a-modal
      :visible="tipVisible"
      dialogClass="step3-action-tip-modal"
      @cancel="tipCancel"
    >
      <template slot="title">
        {{ $t(tipModalMap[tipMode].title) }}
        <a-tooltip placement="right" v-if="tipModalMap[tipMode].ifTextarea">
          <span slot="title">
            {{ $t(tipModalMap[tipMode].titleTip) }}
          </span>
          <a-icon type="question-circle" />
        </a-tooltip>
      </template>
      <div v-if="!tipModalMap[tipMode].ifTextarea" class="center-content">
        {{ $t(tipModalMap[tipMode].content) }}
      </div>
      <template v-else>
        {{ $t(tipModalMap[tipMode].content) }}:
        <a-textarea
          rows="4"
          :placeholder="$t(tipModalMap[tipMode]?.contentPlaceholder)"
          v-model="tipModalMap.backReason"
          class="mt-[10px] mb-[10px]"
        ></a-textarea>
      </template>
      <div slot="footer">
        <!-- 确定 -->
        <a-button
          type="primary"
          v-if="!tipModalMap[tipMode].ifTextarea"
          class="mr-[20px]"
          @click="tipConfirm"
          >{{ $t("user.email.required1111") }}</a-button
        >
        <!-- 取消 -->
        <a-button
          :class="[tipModalMap[tipMode].ifTextarea ? 'mr-[20px]' : '']"
          @click="tipCancel"
          >{{ $t("app.setting.content-width.fluid2222333") }}</a-button
        >
        <!-- 确定 -->
        <a-button
          type="primary"
          v-if="tipModalMap[tipMode].ifTextarea"
          @click="tipConfirm"
          >{{ $t("user.email.required1111") }}</a-button
        >
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  backAction,
  createDataAction,
  createLog,
  deleteAction,
  getActionRemarkList,
  getDataActionDetail,
} from "@/api/dataBreach/form";
import email from "./email.vue";
import step3ActionForm from "./step3ActionForm.vue";
import moment from "moment";
import { createRemark } from "@/api/dataBreach/json";
export default {
  name: "step3Action",
  components: { email, step3ActionForm },
  props: ["actionList", "role", "breachDetail"],
  data() {
    return {
      visible: false,
      title: "",
      type: "",
      childRole: [],
      status: 0,
      form: this.$form.createForm(this),
      lang: localStorage.getItem("lang").includes("zh-CN"),
      ifCanEdit: false,
      tipVisible: false,
      tipMode: "patch",
      tipModalMap: {
        backReason: "",
        patch: {
          title: "breach.steps.step3.action.new.conform.title.tip",
          content: "breach.steps.step3.action.new.conform.patch.content",
          ifTextarea: false,
        },
        ownerSubmit: {
          title: "breach.steps.step3.action.new.conform.title.tip",
          content: "breach.steps.step3.action.new.conform.ownersubmit.content",
          ifTextarea: false,
        },
        approverSubmit: {
          title: "breach.steps.step3.action.new.conform.title.tip",
          content:
            "breach.steps.step3.action.new.conform.approversubmit.content",
          ifTextarea: false,
        },
        back: {
          title: "breach.steps.step2.modal.back.title",
          titleTip: "breach.steps.step3.action.new.conform.back.title.tip",
          content: "breach.steps.step2.modal.back.content",
          contentPlaceholder:
            "breach.steps.step2.modal.back.content.placeholder",
          ifTextarea: true,
        },
        restart: {
          title: "breach.steps.step3.action.new.conform.restart.title",
          titleTip: "breach.steps.step3.action.new.conform.restart.title.tip",
          content: "breach.steps.step3.action.new.conform.restart.content",
          contentPlaceholder:
            "breach.steps.step3.action.new.conform.restart.content.placeholder",
          ifTextarea: true,
        },
      },
      actionDetails: {},
      ifAgree: 1,
      currentData: {},
      initBmwList: [],
    };
  },
  mounted() {
    let that = this;
    window.addEventListener("setItemEvent", function (e) {
      if (e.key == "lang") {
        that.lang = e.value.includes("zh-CN");
      }
    });
  },
  computed: {
    defaultUser() {
      return this.form.getFieldValue("owner");
    },
  },
  methods: {
    async open(type, Id, BreachId) {
      this.type = type;
      this.childRole = [];
      if (this.type === "new") {
        this.childRole.push("processor");
        this.ifCanEdit = true;
        this.title = this.$t("user.verification-code.required11156611052");
        this.status = 1;
        setTimeout(() => {
          this.$refs.step3ActionForm.addInput();
        }, 1500);
        let { data } = await createDataAction({
          BreachId,
          DpiaActionPreset: 2,
        });
        this.currentData = data;
      } else {
        this.title = this.$t(
          this.type === "edit"
            ? "user.verification-code.required11156611057688"
            : "breach.steps.step3.action.view.title"
        );
        this.ifCanEdit = this.type === "edit" ? true : false;
        // 根据Id获取action详情 获取当前角色和状态
        let { data } = await getDataActionDetail({ Id });
        this.currentData = data;
        // 编辑-获取备注列表
        let { data: remarkList } = await getActionRemarkList({
          ActionId: Id,
          ActionType: 1,
        });
        // 获取执行结果和审批意见人员时间回显
        let actionList = [];
        let approveList = [];
        remarkList.forEach((item) => {
          if (item.ActionTitle === "result") {
            actionList.push(item);
          } else if (item.ActionTitle === "approve") {
            approveList.push(item);
          }
        });
        this.actionDetails = {
          actionResult: {
            user: actionList.length
              ? actionList[actionList.length - 1].ActionCreateUserName
              : this.actionCreateUser,
            time: actionList.length
              ? actionList[actionList.length - 1].ActionCreatetime
              : moment().format("YYYY-MM-DD HH:mm:ss"),
          },
          approveResult: {
            user: approveList.length
              ? approveList[approveList.length - 1].ActionCreateUserName
              : this.actionCreateUser,
            time: approveList.length
              ? approveList[approveList.length - 1].ActionCreatetime
              : moment().format("YYYY-MM-DD HH:mm:ss"),
          },
        };
        // 编辑-获取附件列表
        let { data: fileList } = await getActionRemarkList({
          ActionId: Id,
          ActionType: 2,
        });
        // 内容回显
        this.ifAgree = this.currentData.BreachActionDcoStatus;
        setTimeout(() => {
          let childForm = this.$refs.step3ActionForm;
          childForm.inputList = remarkList.filter((item) => {
            return item.ActionTitle !== "approve";
          });
          childForm.fileLists = fileList.map((item) => {
            let urlLists = item.ActionUploadUrl.split("/");
            return {
              uid: item.Id,
              name: urlLists[urlLists.length - 1],
              url: item.ActionUploadUrl,
            };
          });
          if (!childForm.inputList.length) {
            childForm.addInput();
          }
        }, 1500);
        // 处理人processor 负责人owner 审批人approver 共享权限编辑shareEdit
        let rules = {
          owner: data.BreachActionUserId === this.$store.state.user.info.YtId,
          approver: data.BreachActionDcoId === this.$store.state.user.info.YtId,
          processor: this.role.includes("processor"),
          shareEdit: this.role.includes("shareEdit"),
        };
        for (const key in rules) {
          if (Object.hasOwnProperty.call(rules, key)) {
            if (rules[key]) {
              this.childRole.push(key);
            }
          }
        }
        this.status = this.currentData.BreachActionStatus;
      }
      setTimeout(() => {
        // 处理回显值
        this.currentData.BreachActionUserId =
          this.currentData.BreachActionUserId || undefined;
        let userId = this.currentData.BreachActionUserId;
        if (userId) {
          // 去重
          let ifPush = true;
          this.initBmwList.forEach((element) => {
            if (element.value === userId) {
              ifPush = false;
            }
          });
          if (ifPush) {
            this.initBmwList.push({
              label: this.currentData.BreachActionUserResponsible,
              value: this.currentData.BreachActionUserId,
            });
          }
        }
        this.currentData.BreachActionDcoId =
          this.currentData.BreachActionDcoId || undefined;
        setTimeout(() => {
          this.$refs.step3ActionForm.ifApprove =
            this.currentData.BreachActionDcoChoice;
        });
        this.form.setFieldsValue(this.currentData);
      });
      this.visible = true;
    },
    closeModal(ifDel = true) {
      this.visible = false;
      this.form.resetFields();
      this.$refs.step3ActionForm.fileLists = [];
      this.$refs.step3ActionForm.inputList = [];
      this.ifAgree = 1;
      this.$refs.step3ActionForm.ifApprove = 1;
      if (
        this.status === 1 &&
        this.currentData.DpiaActionPreset !== 1 &&
        ifDel
      ) {
        deleteAction({ Id: this.currentData.Id });
      }
    },
    async submit(type) {
      if (type !== "draft") {
        this.form.validateFields(async (err, value) => {
          if (!err) {
            this.tipMode = type;
            if (type !== "ownerSubmit") {
              this.tipVisible = true;
            } else if (type === "ownerSubmit") {
              if (this.$refs.step3ActionForm.ifApprove === 1) {
                this.tipConfirm();
              } else {
                this.tipVisible = true;
              }
            }
          }
        });
      } else if (type === "draft") {
        // 保存草稿
        let { code } = await createDataAction({
          Id: this.currentData.Id,
          BreachId: this.currentData.BreachId,
          ...this.handleInfo(),
        });
        if (code === 1) {
          this.submitRF();
          this.$message.success(
            this.$t("user.verification-code.required111566110577308")
          );
          this.closeModal(false);
        }
      } else {
        // 重启
        this.tipVisible = true;
      }
    },
    tipCancel() {
      this.tipModalMap.backReason = "";
      this.tipVisible = false;
    },
    async tipConfirm() {
      // 提交：分配patch 进行中-提交ownerSubmit 待审批-提交approverSubmit 回退back 重启restart
      let resStatus = -1;
      if (
        this.tipMode === "patch" ||
        this.tipMode === "back" ||
        this.tipMode === "restart"
      ) {
        resStatus = 3;
      } else if (
        this.tipMode === "ownerSubmit" &&
        this.$refs.step3ActionForm.ifApprove === 1
      ) {
        resStatus = 2;
      } else {
        resStatus = 4;
      }
      let { code } = await createDataAction({
        ...this.currentData,
        BreachActionUserId: this.currentData.BreachActionUserResponsible,
        BreachActionStatus: resStatus,
        ...this.handleInfo(),
      });
      if (code === 1) {
        this.submitRF();
        if (
          this.tipMode === "back" ||
          this.tipMode === "patch" ||
          this.tipMode === "ownerSubmit" ||
          this.tipMode === "approverSubmit"
        ) {
          if (this.tipMode === "back") {
            let { code } = await backAction({
              ActionRemarkInfo: this.tipModalMap.backReason,
              ActionId: this.currentData.Id,
            });
            if (code === 1) {
              this.tipVisible = false;
              this.visible = false;
              this.$message.success(
                this.$t("breach.steps.step2.modal.back.tip")
              );
            }
            return;
          }
          // 存log信息
          let logContent = "";
          if (this.tipMode === "patch") {
            logContent =
              "将" +
              this.form.getFieldValue("BreachActionName") +
              "分配给" +
              this.$refs.step3ActionForm.bmwUserList.filter(
                (item) =>
                  item.value === this.form.getFieldValue("BreachActionUserId")
              )[0]?.label;
          } else if (this.tipMode === "ownerSubmit") {
            logContent = resStatus === 4 ? "完成Action" : "提交审核";
          } else {
            logContent = resStatus === 4 ? "审核通过" : "退回";
          }
          createLog({
            BreachId: this.breachDetail?.Id,
            LogUserId: this.$store.state.user.info.YtId,
            LogUserName: this.$store.state.user.info.YtAdminUserName,
            LogOperation: `${this.$store.state.user.info.YtAdminUserName}${logContent}`,
          });
        }
        this.tipCancel();
        this.closeModal(false);
      }
    },
    changeProp(key, value) {
      this[key] = value;
    },
    // 处理form数据
    handleInfo() {
      let tempVal = { ...this.form.getFieldsValue() };
      tempVal.BreachActionStartTime = tempVal.BreachActionStartTime
        ? moment(tempVal.BreachActionStartTime).format("YYYY-MM-DD HH:mm:ss")
        : undefined;
      tempVal.BreachActionFinishTime = tempVal.BreachActionFinishTime
        ? moment(tempVal.BreachActionFinishTime).format("YYYY-MM-DD HH:mm:ss")
        : undefined;
      if (typeof tempVal.BreachActionUserId === "number") {
        tempVal.BreachActionUserId = this.initBmwList.filter(
          (item) => item.value === tempVal.BreachActionUserId
        )[0].label;
      }
      return tempVal;
    },
    // 保存备注和文件 action结果
    async submitRF() {
      this.$refs.step3ActionForm.saveRemarkList(); // 保存备注
      // 保存文件
      let files = this.$refs.step3ActionForm.fileLists
        .filter((item) => item.ifNew)
        .map((item) => {
          return {
            ActionId: this.currentData.Id,
            ActionUploadUrl: item.halfPath,
            ActionType: 2,
            ActionFileName: item.name,
          };
        });
      if (files.length) createRemark(files);
      if (
        this.tipMode === "ownerSubmit" ||
        this.tipMode === "approverSubmit" ||
        this.tipMode === "restart"
      ) {
        // 保存action结果 审批结果 重启原因到备注
        // 结构：按钮类别: [对应action标题, 是否为tipModalMap属性, 属性key]
        let tempMap = {
          ownerSubmit: ["result", false, "BreachActionResult"],
          approverSubmit: ["approve", true, "backReason"],
          restart: ["restart", true, "backReason"],
        };
        createRemark([
          {
            ActionId: this.currentData.Id,
            ActionTitle: tempMap[this.tipMode][0],
            ActionDelete: 2,
            ActionType: 1,
            ActionRemarkInfo: tempMap[this.tipMode][1]
              ? this.tipModalMap[tempMap[this.tipMode][2]]
              : this.form.getFieldValue(tempMap[this.tipMode][2]),
          },
        ]);
      }
      this.$emit("getActionList");
    },
  },
};
</script>

<style lang="less">
.step3-action-modal {
  padding-bottom: 50px;
  .ant-modal-content {
    position: relative;
    overflow: hidden;
    .ant-modal-header {
      border-bottom: 0;
    }
    .ant-modal-body {
      padding: 0 20px;
      .ant-form-item {
        margin-bottom: 12px;
        textarea {
          resize: none;
        }
      }
      .email {
        position: absolute;
        right: -76px;
        top: -76px;
      }
      .self-label {
        color: rgba(0, 0, 0, 0.85);
        line-height: 40px;
      }
      .ant-timeline {
        .ant-form-item-control-wrapper {
          width: 100%;
        }
        .buttons {
          display: flex;
          flex-direction: row-reverse;
        }
      }
      .upload-files {
        width: 100%;
        position: relative;
        & > span:last-child {
          position: absolute;
          color: #8c8c8c;
          top: 6px;
        }
      }
      .if-div {
        border-top: 1px solid #bbb;
        padding: 20px 0 0;
        margin: 10px 0 10px;
      }
    }
    .ant-modal-footer {
      border-top: 0;
      .buttons {
        display: flex;
        justify-content: center;
      }
    }
  }
}
.step3-action-tip-modal {
  .ant-modal-header {
    border-bottom: 0;
    .ant-modal-title {
      position: relative;
      padding-left: 20px;
      &::before {
        content: "";
        height: 100%;
        width: 10px;
        background-color: #5877a1;
        position: absolute;
        left: 0;
        top: 0;
      }
    }
  }
  .ant-modal-body {
    .center-content {
      width: 100%;
      text-align: center;
    }
    textarea {
      resize: none;
    }
  }
  .ant-modal-footer {
    border-top: 0;
    display: flex;
    justify-content: center;
  }
}
</style>